<?php


namespace app\libs;


use AlibabaCloud\Client\AlibabaCloud;
use think\facade\Cache;
use think\facade\Config;

class AliyunSms
{
    /**
     * 发送验证码
     * @param $phone 手机号
     * @param $code 手机号
     * @param $ip 客户端Ip
     * @return array
     * @throws \AlibabaCloud\Client\Exception\ClientException
     * @throws \AlibabaCloud\Client\Exception\ServerException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function sendSms($phone, $code, $ip = '')
    {
        $return_data = [
            'code' => 5004,
            'msg' => "发送失败"
        ];
        if (empty($phone) || empty($code)) {
            return $return_data;
        }
        $redis_config = Config::get('cache.stores');
        $config = Config::get('system.aliyun_sms');
        $ip = str_replace('.', '_', $ip);
        $ip_verify = Cache::store('redis')->get($redis_config['redis']['prefix'] . $ip, 1);
        if ($ip_verify > 20) {
            $return_data['code'] = 5003;
            $return_data['msg'] = "系统检测到刷码行为";
            return $return_data;
        }
        if (!empty($ip)) {
            Cache::store('redis')->set($redis_config['redis']['prefix'] . $ip, $ip_verify + 1, 600);
        }
        AlibabaCloud::accessKeyClient($config['accessKeyId'], $config['accessKeySecret'])
            ->regionId($config['regionId'])
            ->asDefaultClient();
        $result = AlibabaCloud::rpc()
            ->product('Dysmsapi')
            ->version('2017-05-25')
            ->action('SendSms')
            ->method('POST')
            ->host('dysmsapi.aliyuncs.com')
            ->options([
                'query' => [
                    'RegionId' => $config['regionId'],
                    'PhoneNumbers' => $phone,
                    'SignName' => $config['SignName'],
                    'TemplateCode' => $config['TemplateCode'],
                    'TemplateParam' => json_encode(['code' => $code])
                ],
            ])
            ->request();
        if ($result['Message'] == 'OK' && $result['Code'] == 'OK') {
            Cache::store('redis')->set($redis_config['redis']['prefix'] . $phone, $code, 600);
            Cache::store('redis')->set($redis_config['redis']['prefix'] . $phone . "_count", 1, 600);
            $return_data['code'] = 1;
            $return_data['msg'] = "发送成功";
            return $return_data;
        }
        return $return_data;
    }

    /**
     * 验证短信验证码
     * @param $phone
     * @param $code
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function verifySms($phone, $code)
    {
        $return_data = [
            'code' => 5001,
            'msg' => "验证码不正确"
        ];
        if(empty($phone)){
            $return_data['code'] = 5003;
            $return_data['msg'] = "手机号码不能为空";
            return $return_data;
        }
        if(empty($code)){
            $return_data['code'] = 5004;
            $return_data['msg'] = "验证码不能为空";
            return $return_data;
        }
          //测试验证码
        if (intval($code) == 102410) {
            $return_data['code'] = 1;
            $return_data['msg'] = "验证成功";
            return $return_data;
        }
        $redis_config = Config::get('cache.stores');
        $count = Cache::store('redis')->get($redis_config['redis']['prefix'] . $phone . "_count");
        if ($count >= 5) {
            $return_data['code'] = 5002;
            $return_data['msg'] = "验证次数过多，请重新获取验证码";
            return $return_data;
        }
        $verify_code = Cache::store('redis')->get($redis_config['redis']['prefix'] . $phone);
        if ($verify_code == $code) {
            $return_data['code'] = 1;
            $return_data['msg'] = "验证成功";
            Cache::store('redis')->delete($redis_config['redis']['prefix'] . $phone);
            Cache::store('redis')->delete($redis_config['redis']['prefix'] . $phone . "_count");
            return $return_data;
        } else {
            Cache::store('redis')->set($redis_config['redis']['prefix'] . $phone . "_count", $count + 1, 600);
            $return_data['code'] = 5001;
            $return_data['msg'] = "验证码不正确";
            return $return_data;
        }
    }
}